package com.njupt.sso.service.impl;

import com.mysql.fabric.xmlrpc.base.Data;
import com.njupt.common.pojo.JsonUtils;
import com.njupt.common.pojo.TaotaoResult;
import com.njupt.jedis.JedisClient;
import com.njupt.mapper.TbUserMapper;
import com.njupt.pojo.TbUser;
import com.njupt.pojo.TbUserExample;
import com.njupt.sso.service.UserService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.Date;
import java.util.List;
import java.util.UUID;
import java.util.zip.DataFormatException;

/**
 * @Author: XJL
 * @Description:用户处理
 * @Date: Create in 20:51 2018/6/3
 * @Modified By:
 **/
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private TbUserMapper tbUserMapper;

    @Autowired
    private JedisClient jedisClient;

    @Value("${USER_SESSION}")
    private String USER_SESSION;

    @Value("${SESSION_EXPIRE}")
    private Integer SESSION_EXPIRE;

    @Override
    public TaotaoResult checkData(String data, int type) {

        //根据type查询
        TbUserExample example = new TbUserExample();
        TbUserExample.Criteria criteria = example.createCriteria();
        //设置条件：1 username; 2 phone; 3  emaial
        if (type==1){
            criteria.andUsernameEqualTo(data);
        }else if (type==2){
            criteria.andPhoneEqualTo(data);
        }else if (type==3){
            criteria.andEmailEqualTo(data);
        }else {
            return TaotaoResult.build(400,"illege parameter!");

        }
        List<TbUser> list = tbUserMapper.selectByExample(example);
        if (list!=null&&list.size()>0){
            //数据不可用
            return TaotaoResult.ok(false);
        }
        return TaotaoResult.ok(true);

    }

    @Override
    public TaotaoResult registerUser(TbUser tbUser) {

        if (StringUtils.isBlank(tbUser.getUsername())){
            return TaotaoResult.build(400,"用户名不能为空");
        }
        //判断用户名是否重复
        TaotaoResult result = checkData(tbUser.getUsername(),1);
        if (!(Boolean) result.getData()){
            return TaotaoResult.build(400,"用户名重复");

        }
        if (StringUtils.isBlank(tbUser.getPassword())){
            return TaotaoResult.build(400,"密码不能为空");
        }
        //校验phonenum，是否为空，是否重复
        if (StringUtils.isNotBlank(tbUser.getPhone())){
            result = checkData(tbUser.getPhone(),2);
            if (!(Boolean) result.getData()){
                return TaotaoResult.build(400,"手机号重复");
            }
        }
        //校验email,是否为空，是否重复
        if (StringUtils.isNotBlank(tbUser.getEmail())){
            result = checkData(tbUser.getEmail(),3);
            if (!(Boolean) result.getData()){
                return TaotaoResult.build(400,"email重复");
            }
        }

        String myPass = DigestUtils.md5DigestAsHex(tbUser.getPassword().getBytes());
        tbUser.setPassword(myPass);
        tbUser.setUpdated(new Date());
        tbUser.setCreated(new Date());
        //向数据库插入数据
        tbUserMapper.insert(tbUser);
        return TaotaoResult.ok();
    }

    @Override
    public TaotaoResult login(String username, String password) {

        //判断用户名和密码是否正确
        TbUserExample example = new TbUserExample();
        TbUserExample.Criteria criteria = example.createCriteria();
        criteria.andUsernameEqualTo(username);
        List<TbUser> list = tbUserMapper.selectByExample(example);
        if (list==null||list.size()==0){
            return TaotaoResult.build(400,"用户名或密码不正确！");
        }
        //密码进行MD5加密
        TbUser user = list.get(0);
        if (!DigestUtils.md5DigestAsHex(password.getBytes()).equals(user.getPassword())){
            return TaotaoResult.build(400,"用户名或密码不正确！");
        }
        //生成token
        String token = UUID.randomUUID().toString();
        //用户信息保存到redis，key为token，value为用户信息

        //为了安全，密码清空
        user.setPassword(null);
        jedisClient.set(USER_SESSION+":"+token, JsonUtils.objectToJson(user));

        //设置key的过期时间
        jedisClient.expire(USER_SESSION+":"+token,SESSION_EXPIRE);
        //返回登陆成功，把token返回


        return TaotaoResult.ok(token);
    }

    @Override
    public TaotaoResult getUserByToken(String token) {
        //从redis中取token信息
        String userJson = jedisClient.get(USER_SESSION+":"+token);
        //若不存在，说明数据已经过期
        if (StringUtils.isBlank(userJson)){
            return TaotaoResult.build(400,"用户数据以过期，请重新登陆！");
        }
        //存在，则重新设置过期时间，并将其转换成TbUser对象并并返回
        jedisClient.expire(USER_SESSION+":"+token,SESSION_EXPIRE);
        TbUser user = JsonUtils.jsonToPojo(userJson,TbUser.class);

        return TaotaoResult.ok(user);
    }

    @Override
    public TaotaoResult logout(String token) {

        Long result = jedisClient.del(USER_SESSION+":"+token);
        if (result!=1){
            return TaotaoResult.build(400,"退出失败");
        }
        return TaotaoResult.ok();
    }
}
